/*
 * Copyright (c) 2020 - present, Inspur Genersoft Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package io.iec.edp.caf.lock.service.memory;

import io.iec.edp.caf.lockservice.api.IDistributedLock;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.locks.Lock;

@Deprecated
public class MemoryLockOld  implements IDistributedLock {
    private boolean isAcquired;
    /**
     * 加锁资源
     */
    private String resource;
    private static ConcurrentHashMap<String, Lock> map;
    private final ConcurrentHashMap<String, Integer> refs;

    public MemoryLockOld(String resource, boolean isAcquired, ConcurrentHashMap<String, Lock> map, ConcurrentHashMap<String, Integer> refs) {
        this.resource = resource;
        this.isAcquired = isAcquired;
        this.map = map;
        this.refs = refs;
    }


    @Override
    public String getResource() {
        return this.resource;
    }

    /**
     * 是否已正常获取锁
     *
     * @return
     */
    public boolean isAcquired() {
        if (this.isAcquired) {
            return true;
        }
        return false;
    }


    @Override
    public void close() {
        if (this.isAcquired) {
            synchronized (resource) {
                if (refs.computeIfPresent(resource, (k, v) -> v - 1) == 0) {
                    refs.remove(resource);
                    map.remove(resource);
                }
                map.get(resource).unlock();
            }
        }
    }
}
